import io
from DrissionPage import ChromiumPage
from DrissionPage.common import Keys
from PIL import Image
from ddddocr import DdddOcr
import cairosvg
import re
import cv2
import numpy as np



# 创建DdddOcr对象
ocr = DdddOcr(show_ad=False)
class SougouPushAutomation:
    def __init__(self,page:ChromiumPage)-> None:
        self.page = page
        
    def start(self,url,username,password):       
        # 跳转到登录页面
        self.page.get(url)
        self.page.ele('xpath=/html/body/div/header/div/div/a[1]').click()
        # 定位到账号文本框，获取文本框元素，输入对文本框输入账号
        self.page.ele('xpath=/html/body/div/div[2]/div/div/div[2]/div[1]/input').input(username)
        # 定位到密码文本框并输入密码
        self.page.ele('xpath=/html/body/div/div[2]/div/div/div[2]/div[2]/input').input(password)
        # 验证码
        while True:
            try:
                self.page.wait(0.2)
                self.page.ele('xpath=/html/body/div/div[2]/div/div/div[2]/div[3]/input').clear()
                self.page.ele('xpath=/html/body/div/div[2]/div/div/div[2]/div[3]/a/img').click()
                svg_data = self.page.ele('xpath=/html/body/div/div[2]/div/div/div[2]/div[3]/a/img').src()
                # 读取图片文件
                # 将字节字符串解码为普通字符串
                decoded_string = svg_data.decode('utf-8')
                path_pattern = r'<path [^>]*fill="none"[^>]*?>'
                replaced_string = re.sub(path_pattern, '', decoded_string)
                # 将替换后的字符串编码回字节字符串
                encoded_string = replaced_string.encode('utf-8')
                png_data = cairosvg.svg2png(bytestring=encoded_string)
                image_data = Image.open(io.BytesIO(png_data))
                image_data.save('captcha.png')
                result_path =  self.processed_captcha('captcha.png')
                captcha_data = Image.open(result_path)
                # 识别图片验证码
                yzm = ocr.classification(captcha_data)
                print(yzm)
                self.page.ele('xpath=/html/body/div/div[2]/div/div/div[2]/div[3]/input').input(yzm)
                # 点击登录按钮
                self.page.ele('xpath=/html/body/div/div[2]/div/div/div[4]/a').click()
            except BaseException as err:
                break


    def article_manage(self):
        self.page.wait(0.5)
        # 进入资源收录页
        self.page.ele('xpath=/html/body/div/header/div/ul/li[1]/a').hover()
        self.page.ele('xpath=/html/body/div/header/div/ul/li[1]/div/div/div[1]/div/ul/li[1]/a').click()

    def article_copy(self,domain_name,webseo):
        # 选择要推送的域名
        self.page.wait.ele_displayed('xpath=/html/body/div/div/div/div/div[2]/div/div[3]/div[2]/div[1]/span[2]/div/div/div[1]/div[1]')
        self.page.ele('xpath=/html/body/div/div/div/div/div[2]/div/div[3]/div[2]/div[1]/span[2]/div/div/div[1]/div[2]/b').click()
        self.page.ele(domain_name).click()
        for iurl in webseo:
            # 输入页面地址
            self.page.ele('xpath=/html/body/div/div/div/div/div[2]/div/div[3]/div[2]/div[2]/div/textarea').input(iurl)
            self.page.actions.key_down(Keys.ENTER)
        # 输入验证码
        # 验证码
        while True:
            self.page.wait(0.5)
            self.page.ele('xpath=/html/body/div/div/div/div/div[2]/div/div[3]/div[2]/div[4]/div[1]/input').clear()
            self.page.ele('xpath=/html/body/div/div/div/div/div[2]/div/div[3]/div[2]/div[4]/div[1]/a[1]/img').click()
            svg_data = self.page.ele('xpath=/html/body/div/div/div/div/div[2]/div/div[3]/div[2]/div[4]/div[1]/a[1]/img').src()
            # 读取图片文件
            # 将字节字符串解码为普通字符串
            decoded_string = svg_data.decode('utf-8')
            path_pattern = r'<path [^>]*fill="none"[^>]*?>'
            replaced_string = re.sub(path_pattern, '', decoded_string)
            # 将替换后的字符串编码回字节字符串
            encoded_string = replaced_string.encode('utf-8')
            png_data = cairosvg.svg2png(bytestring=encoded_string)
            image_data = Image.open(io.BytesIO(png_data))
            image_data.save('captcha.png')
            result_path =  self.processed_captcha('captcha.png')
            captcha_data = Image.open(result_path)
            # 识别图片验证码
            yzm = ocr.classification(captcha_data)
            print(yzm)
            
            self.page.ele('xpath=/html/body/div/div/div/div/div[2]/div/div[3]/div[2]/div[4]/div[1]/input').input(yzm)
            # 点击提交
            self.page.wait.ele_displayed('xpath=/html/body/div/div/div/div/div[2]/div/div[3]/div[2]/div[4]/div[2]/a')
            self.page.ele('xpath=/html/body/div/div/div/div/div[2]/div/div[3]/div[2]/div[4]/div[2]/a').click('js')
            self.page.wait(0.2)
            try:
                self.page.ele('xpath=/html/body/div/div/div/div/div[2]/div/div[4]/div/div[2]/div[2]/a',timeout=1.5).click()
                break
            except BaseException as err:
                pass
        
        
    def processed_captcha(self,image_path)->str:
        # 读取图片
        image = cv2.imread(image_path)

        # 转换为灰度图
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # 使用阈值进行二值化
        _, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)

        # 如果需要，可以进行形态学操作来平滑图像
        kernel = np.ones((2,2), np.uint8)
        binary = cv2.dilate(binary, kernel, iterations=2)
        binary = cv2.erode(binary, kernel, iterations=2)

        # 寻找轮廓
        contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        # 创建一个与原始图像大小相同的黑色背景图像
        white_bg = np.ones_like(image) * 255

        # 遍历轮廓并绘制
        for contour in contours:
            # 计算轮廓的边界框
            x, y, w, h = cv2.boundingRect(contour)
        
            # 根据需要可以设置最小宽度或高度，去除小轮廓
            if cv2.contourArea(contour) > 100:
            
                # 将原始图像中轮廓内的部分复制到黑色背景图像上
                mask = np.zeros_like(gray)
                cv2.drawContours(mask, [contour], -1, 255, -1)
                white_bg[y:y+h, x:x+w] = image[y:y+h, x:x+w]
        # 保存结果到文件
        result_path = 'result.jpg'
        cv2.imwrite(result_path, white_bg)
        
        return result_path
